import 'package:shared_preferences/shared_preferences.dart';

class TokenManager {
  final String _tokenKey = 'token';
  String? _token;

  //创建单例
  static TokenManager? _instance;

  // 私有构造函数
  TokenManager._internal();

  // 工厂构造函数
  factory TokenManager() {
    _instance ??= TokenManager._internal();
    return _instance!;
  }

  //初始化
  Future<void> init() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    _token = prefs.getString(_tokenKey) ?? '';
  }

  //获取token
  String getToken() {
    return _token ?? '';
  }

  //修改token
  Future<void> setToken(String token) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    _token = token;
    await prefs.setString(_tokenKey, token);
  }

  //删除token
  Future<void> removeToken() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    _token = '';
    await prefs.remove(_tokenKey);
  }
}
